using Godot;
using System;
using System.Threading.Tasks;
public partial class DialogueSystemCoroutine : Control
{
	[Export] private RichTextLabel  dialogueLabel;
	private float charactersPerSecond = 20f;
	[Signal]
	public delegate void MyCallableSignalEventHandler();
	
	private string fullText ;
	private bool isTyping = false;
	private async Task TypeTextCoroutine(string text)
	{
		fullText = text;
		dialogueLabel.Text = "";
		isTyping = true;
		
		float delay = 1f / charactersPerSecond;
		
		for (int i = 0; i < text.Length; i++)
		{
			dialogueLabel.Text += text[i];
			
			// 等待指定的时间
			await ToSignal(GetTree().CreateTimer(delay), "timeout");
			
			// 如果被跳过，提前结束
			if (!isTyping)
			{
				dialogueLabel.Text = fullText;
				break;
			}
		}
		
		isTyping = false;
	}

	// 开始对话
	public async void StartDialogue(string text)
	{
		if (isTyping)
		{
			SkipTyping();
			await ToSignal(GetTree().CreateTimer(0.1f), "timeout");
		}
		
		await TypeTextCoroutine(text);
		EmitSignal(SignalName.MyCallableSignal);
	}

	// 跳过打字
	public void SkipTyping()
	{
		isTyping = false;
	}
	
	
}
